package cn.edu.nchu.fragmentdemo.fragments;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.j256.ormlite.dao.Dao;

import java.util.ArrayList;
import java.util.List;

import cn.edu.nchu.fragmentdemo.MainActivity;
import cn.edu.nchu.fragmentdemo.R;
import cn.edu.nchu.fragmentdemo.adapter.RouteTaskAdapter;
import cn.edu.nchu.fragmentdemo.db.dao.RouteTaskDao;
import cn.edu.nchu.fragmentdemo.bean.RouteTask;
import cn.edu.nchu.fragmentdemo.db.server.RouteTaskDataServer;
import cn.edu.nchu.fragmentdemo.view.SlideRecyclerView;
import lombok.SneakyThrows;


/**
 * @className: UavRouteTaskFragment
 * @description: TODO 类描述
 * @author: Kuangkeli
 * @date: 2023/09/25 14:53
 **/
public class UavRouteTaskFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {


    private String TAG = "UavRouteTaskFragment";
    /**
     * 下拉刷新布局
     */
    private SwipeRefreshLayout mSwipeRefreshLayout;
    /**
     * 航线任务Dao
     */
    Dao<RouteTask, Integer> routeTaskDao;
    /**
     * 悬浮按钮
     */
    private FloatingActionButton addRouteTaskBtn;
    private FloatingActionButton btnShowButton;
    /**
     * 自定义滑动删除RecyclerView
     */
    private SlideRecyclerView recycler_view_list;

    private LinearLayoutManager mLayoutManager;
    /**
     * 当前最后一项的编号  position
     */
    private int lastVisibleItem = 0;
    /**
     * 每一页限制的个数
     */
    private final int PAGE_COUNT = 8;
    /**
     * 添加一个标志来记录按钮的可见性状态
     */
    private boolean isButtonVisible = true;
    /**
     * 当前页码
     */
    private final int CURRENT_PAGE = 1;

    /**
     * 航线任务适配器
     */
    private RouteTaskAdapter routeTaskAdapter;

    private ConstraintLayout constraintLayout;
    /**
     * 当前航线任务列表
     */
    private List<RouteTask> routeTaskList;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private Button editRouteTask;

    private Button closePageBtn;

    private MainActivity mainActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_uav_route_task, container, false);
        recycler_view_list = rootView.findViewById(R.id.recycler_view_list);
        mainActivity = (MainActivity) MainActivity.getActivity();
        mSwipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        addRouteTaskBtn = rootView.findViewById(R.id.add_route_task_btn);
        btnShowButton = rootView.findViewById(R.id.btnShowButton);
        constraintLayout = rootView.findViewById(R.id.fragment_panel);
        closePageBtn = rootView.findViewById(R.id.btnCloseList);
        return rootView;
    }

    @SneakyThrows
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        routeTaskDao = RouteTaskDao.getRouteTaskDao(requireContext());
        routeTaskList = new ArrayList<>();
        requestData(RouteTaskDataServer.getMaxId(routeTaskDao), PAGE_COUNT);
        routeTaskAdapter = new RouteTaskAdapter(requireContext(), routeTaskList, routeTaskList.size() > 0 ? true : false);
        recycler_view_list.setAdapter(routeTaskAdapter);
        /**
         * 初始化点击事件监听器
         */
        initClickListener();
    }


    /**
     * 初始化点击事件监听器
     */
    private void initClickListener() {

        /**
         * 滚动分页加载监听器
         */
        mLayoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false);
        recycler_view_list.setLayoutManager(mLayoutManager);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.divider_inset));
        recycler_view_list.addItemDecoration(itemDecoration);
        recycler_view_list.setItemAnimator(new DefaultItemAnimator());
        recycler_view_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    routeTaskAdapter.setFadeTips(false);
                    if (routeTaskAdapter.isFadeTips() == false && lastVisibleItem + 1 == routeTaskAdapter.getItemCount()) {
                        // 然后调用updateRecyclerview方法更新RecyclerView
                        updateRecyclerView(routeTaskList.get(routeTaskList.size() - 1).getId(), PAGE_COUNT);
                    }
                    if (routeTaskAdapter.isFadeTips() && lastVisibleItem + 2 == routeTaskAdapter.getItemCount()) {
                        // 然后调用updateRecyclerview方法更新RecyclerView
                        updateRecyclerView(routeTaskList.get(routeTaskList.size() - 1).getId(), PAGE_COUNT);
                    }
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

        /**
         * 删除按钮事件监听器
         */


        OnCustomButtonClickListener(routeTaskAdapter);

        OnDeleteClickListener(routeTaskAdapter);

        /**
         * 新增航线按钮事件监听器
         */
        addRouteTaskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出新增航点任务窗口的逻辑
                showAddRouteTaskDialog();
            }
        });
        /**
         * 按钮收纳事件监听器
         */
        btnShowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭当前 Fragment 的逻辑
                ShowButton();
            }
        });

        /**
         * 关闭按钮事件监听器
         */
        closePageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭当前 Fragment 的逻辑
                mainActivity.clearFragmentByTag(TAG);
                Button button = mainActivity.findViewById(R.id.btnOpenPage);
                button.setVisibility(View.VISIBLE);
            }
        });

    }

    public String getTAG() {
        return TAG;
    }

    /**
     * 请求数据并通知适配器更新界面
     */
    private void updateRecyclerView(int fromIndex, int count) {
        routeTaskAdapter.setFadeTips(false);
        requestData(fromIndex, count);
        routeTaskAdapter.notifyDataSetChanged();
    }

    /**
     * 滑动删除事件
     *
     * @param routeTaskAdapter
     */
    public void OnDeleteClickListener(final RouteTaskAdapter routeTaskAdapter) {
        routeTaskAdapter.setOnDeleteClickListener(new RouteTaskAdapter.OnDeleteClickLister() {
            @Override
            public void onDeleteClick(View view, final int position) {
                new AsyncTask<Void, Void, List<RouteTask>>() {
                    @SneakyThrows
                    @Override
                    protected List<RouteTask> doInBackground(Void... voids) {
                        // 获取要删除的对象
                        RouteTask routeTask = routeTaskList.get(position);
                        // 执行删除操作
                        routeTaskDao.delete(routeTask);
                        routeTaskList.remove(routeTask);
                        // 返回所有任务列表
                        return routeTaskList;
                    }

                    @Override
                    protected void onPostExecute(final List<RouteTask> updatedTaskList) {
                        routeTaskAdapter.setFadeTips(true);
                        // 更新列表数据和界面
                        routeTaskAdapter.notifyDataSetChanged();
                        recycler_view_list.closeMenu();
                    }
                }.execute();
            }
        });
    }


    /**
     * 点击itemView的事件  弹出编辑/上传面板  编辑面板需要传递对应的RouteTask
     *
     * @param routeTaskAdapter
     */
    public void OnCustomButtonClickListener(final RouteTaskAdapter routeTaskAdapter) {
        routeTaskAdapter.setOnCustomButtonClickListener(new RouteTaskAdapter.OnCustomButtonClickListener() {
            @Override
            public void onCustomButtonClick(View view, final int position) {
                if (constraintLayout.getVisibility() == View.VISIBLE) {
                    constraintLayout.setVisibility(View.GONE);
                } else {
                    editRouteTask = constraintLayout.findViewById(R.id.editTaskButton);
                    constraintLayout.setVisibility(View.VISIBLE);

                    editRouteTask.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            constraintLayout.setVisibility(View.GONE);
                            //用于退出左侧航线任务栏
                            mainActivity.clearFragmentByTag(TAG);
                            Button button = mainActivity.findViewById(R.id.btnOpenPage);
                            button.setVisibility(View.VISIBLE);

                            //实例右侧航线航点设置栏 利用bundle传递点击的ItemView对应的RouteTaskId
                            UavSettingBarFragment uavSettingBarFragment = new UavSettingBarFragment();
                            int routeTaskId = routeTaskList.get(position).getId();
                            Bundle bundle = new Bundle();
                            bundle.putInt("routeTaskId", routeTaskId);
                            uavSettingBarFragment.setArguments(bundle);
                            mainActivity.replaceRightFragment(uavSettingBarFragment);
                        }
                    });


                }
            }
        });
    }

    /**
     * 新增航线任务Dialog
     */
    private void showAddRouteTaskDialog() {

        // 在这里实现弹出新增航点任务窗口的逻辑
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("添加航点任务");

        // 创建自定义布局
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        final View dialogView = inflater.inflate(R.layout.add_route_task_dialog, null);
        builder.setView(dialogView);

        // 设置对话框按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取输入的航点任务信息，并执行相应操作
                EditText editTextTaskName = dialogView.findViewById(R.id.editTextTaskName);
                EditText editTextLocation = dialogView.findViewById(R.id.editTextLocation);

                String taskName = editTextTaskName.getText().toString();
                String location = editTextLocation.getText().toString();

                // 创建一个新的RouteTask对象，并设置相关属性
                final RouteTask routeTask = new RouteTask();
                routeTask.setTaskName(taskName);
                routeTask.setLocation(location);

                // 设置创建时间为当前时间
                routeTask.setCreateTime(System.currentTimeMillis());
                routeTask.setUpdateTime(System.currentTimeMillis());
                /**
                 *  在后台线程执行数据库操作
                 */
                addRouteTask(routeTaskAdapter, routeTask);

            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消按钮点击事件的逻辑
                dialog.dismiss(); // 关闭对话框
            }
        });

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 用于新增航线任务 插入到数据库中 并通知适配器更新视图
     *
     * @param routeTaskAdapter
     * @param routeTask
     */
    private void addRouteTask(final RouteTaskAdapter routeTaskAdapter, final RouteTask routeTask) {
        new AsyncTask<Void, Void, List<RouteTask>>() {
            @SneakyThrows
            @Override
            protected List<RouteTask> doInBackground(Void... voids) {
                // 创建RouteTask对象并插入到数据库中
                routeTaskDao.create(routeTask);
                routeTaskList.add(0, routeTask);
                // 返回所有任务列表
                return routeTaskList;
            }

            @Override
            protected void onPostExecute(final List<RouteTask> taskList) {
                routeTaskAdapter.setFadeTips(true);
                // 更新列表数据和界面
                routeTaskAdapter.notifyDataSetChanged();
                recycler_view_list.closeMenu();
            }
        }.execute();
    }

    /**
     * 按钮收纳
     */
    private void ShowButton() {
        if (isButtonVisible) {
            // 隐藏上方按钮
            addRouteTaskBtn.setVisibility(View.GONE);
            // 切换自己的图片
            btnShowButton.setImageResource(R.drawable.uav_show_button);
            isButtonVisible = false;
        } else {
            // 显示上方按钮
            addRouteTaskBtn.setVisibility(View.VISIBLE);
            // 切换回原来的图片
            btnShowButton.setImageResource(R.drawable.uav_close);
            isButtonVisible = true;
        }
    }

    /**
     * 用于向数据库请求数据  开始位置  请求个数
     *
     * @param start
     * @param count
     */
    public void requestData(final int start, final int count) {
        final int oldSize = routeTaskList.size();
        new AsyncTask<Void, Void, List<RouteTask>>() {
            @SneakyThrows
            @Override
            protected List<RouteTask> doInBackground(Void... voids) {
                // 返回当前页数据
                return RouteTaskDataServer.getData(start, count, routeTaskDao);
            }

            @Override
            protected void onPostExecute(final List<RouteTask> taskList) {
                routeTaskList.addAll(taskList);
                if (routeTaskList.size() > oldSize) {
                    routeTaskAdapter.updateList(true);
                } else {
                    routeTaskAdapter.updateList(false);
                }
            }
        }.execute();
    }


    /**
     * 下拉刷新的事件函数   用于刷新数据以及重新适配
     */
    private void refreshData() {
        // 关闭下拉刷新动画
        mSwipeRefreshLayout.setRefreshing(true);

        // 更新数据集合

        // 延迟两秒关闭动画
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast toast = Toast.makeText(requireContext(), "已刷新", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP | Gravity.START, 200, 1200); // 设置Toast弹出在顶部左侧
                toast.show();
            }
        }, 1000);


    }


    @Override
    public void onRefresh() {
        refreshData();
    }
}



